<?php
namespace App\Admin\Controllers;

use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

use App\Admin\Actions\DataTable;
use App\Admin\Actions\SoftDelete;
use App\Admin\Actions\Create;
use App\Admin\Actions\Update;
use App\Admin\Actions\Delete;
use App\Models\User;

class UserController extends Controller
{
	use DataTable, SoftDelete, Create, Update, Delete;

	/**
	 * GET	    /user	        index	user.index
	 * POST	    /user	        store	user.store
	 * GET	    /user/{user}	show	user.show
	 * PUT	    /user/{user}	update	user.update
	 * DELETE	/user/{user}	destroy	user.destroy
	 * 
	 * PUT   	/user/restore	restore       
	 * PUT   	/user/delete	delete        //普通删除
	 * DELETE	/user/delete	forceDelete   //物理删除
	 */
	public function modelName()
	{
		return User::class;
	}

	public function dataTable($setter)
	{
		$setter->validate(function($request){
			return $request->validate([
        		'name'=>'nullable|string|max:20',
        		'email'=>'nullable|email',
			]);
		});

		$setter->search(function($query, $validated){
			if( !empty($validated['name']) ){
				$query->where('name', $validated['name']);
			}
			if( !empty($validated['email']) ){
				$query->where('email', $validated['email']);
			}
		});
	}

	public function actionStore($setter)
	{
		$setter->validate(function($request){
			return $request->validate([
				// 'email'    => 'required|email',
				'email'    => 'required|email|unique:users',
				'name'     => 'required|alpha_num',
				'password' => 'required|string|between:6,20',
			], [
				'required' => ':attribute不能为空',
				'email.unique' => '邮箱已存在',
			], [
				'email' => '邮箱',
				'name' => '昵称',
				'password' => '密码',
			]);
		});
	}

	public function actionUpdate($setter)
	{
		$setter->validate(function($request, $model){
			$unique = Rule::unique(User::class)->ignore($model);
			return $request->validate([
				'email'    => ['sometimes', 'email', $unique],
				'name'     => 'sometimes|alpha_num',
				'password' => 'sometimes|string|between:6,20',
				'email_verified_status' => 'sometimes|boolean',
			], [
				'email.unique' => '邮箱已存在',
			], [
				'email' => '邮箱',
				'name' => '昵称',
				'password' => '密码',
			]);
		});

		$setter->handle(function($model, $validated){
			if( isset($validated['email_verified_status']) ){
				if( $validated['email_verified_status'] && $model->email_verified_at==null ){
					$model->email_verified_at = now();
				}elseif( !$validated['email_verified_status'] && $model->email_verified_at!==null ){
					$model->email_verified_at = null;
				}
			}

			return $model->update($validated);
		});
	}



	public function actionRestore($setter)
	{

	}

	public function actionForceDelete($setter)
	{

	}

}
